﻿using System;
using System.Configuration;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Collections;

namespace JCode.DBUtility
{
    public abstract class SQLHelper
    {
        //Database connection strings
        private static readonly string StrConn = ConfigurationManager.AppSettings["sqlconn"];


        #region 执行存储过程返回datareader
        /// <summary>
        /// 执行存储过程返回datareader
        /// </summary>
        /// <param name="storedProcName"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public static SqlDataReader GetDataReader_Proc(string storedProcName, SqlParameter[] parameters)
        {
            SqlConnection conn = new SqlConnection(StrConn);
            if (conn.State == ConnectionState.Closed)
                conn.Open();
            SqlCommand cmd = new SqlCommand(storedProcName, conn);
            cmd.CommandType = CommandType.StoredProcedure;

            foreach (SqlParameter parameter in parameters)
            {
                //      if (parameter != null)
                cmd.Parameters.Add(parameter);
            }

            try
            {

                return cmd.ExecuteReader(CommandBehavior.CloseConnection);

            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }

        }
        #endregion
        #region 执行存储过程返回dataset
        /// <summary>
        /// 执行存储过程返回dataset
        /// </summary>
        /// <param name="procName">存储过程名</param>
        /// <param name="parameters">参数</param>
        /// <returns></returns>
        public static DataSet GetDataSet_Proc(string procName, SqlParameter[] parameters)
        {
            using (SqlConnection conn = new SqlConnection(StrConn))
            {
                DataSet ds = new DataSet();
                try
                {
                    if (conn.State == ConnectionState.Closed)
                        conn.Open();
                    SqlDataAdapter adapter = new SqlDataAdapter(procName, conn);
                    adapter.SelectCommand.CommandType = CommandType.StoredProcedure;
                    foreach (SqlParameter parameter in parameters)
                    {
                        adapter.SelectCommand.Parameters.Add(parameter);
                    }

                    adapter.SelectCommand.CommandTimeout = 300;
                    adapter.Fill(ds);
                    adapter.Dispose();
                    adapter = null;

                }
                catch (Exception e)
                {
                    throw new Exception(e.Message);
                }
                finally
                {
                    conn.Close();
                }
                return ds;
            }


        }

        #endregion
        #region 执行存储过程 返回影响的行数
        public static int ExecNonQuery_Proc(string storedProcName, SqlParameter[] parameters)
        {
            using (SqlConnection conn = new SqlConnection(StrConn))
            {
                if (conn.State == ConnectionState.Closed)
                    conn.Open();
                SqlCommand cmd = new SqlCommand(storedProcName, conn);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandTimeout = 300;
                foreach (SqlParameter parameter in parameters)
                {
                    cmd.Parameters.Add(parameter);
                }
                int rowsAffected = cmd.ExecuteNonQuery();


                conn.Close();
                return rowsAffected;

            }
        }
        #endregion

        #region 执行存储过程 返回return
        public static object ExecNonQueryReturn_Proc(string storedProcName, SqlParameter[] parameters)
        {
            using (SqlConnection conn = new SqlConnection(StrConn))
            {
                if (conn.State == ConnectionState.Closed)
                    conn.Open();
                SqlCommand cmd = new SqlCommand(storedProcName, conn);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandTimeout = 300;
                foreach (SqlParameter parameter in parameters)
                {
                    cmd.Parameters.Add(parameter);
                }
                cmd.Parameters.Add("RETURN_VALUE", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
                cmd.ExecuteNonQuery();

                object o = cmd.Parameters["RETURN_VALUE"].Value;
                conn.Close();
                return o;

            }
        }
        #endregion
        #region 执行存储过程，返回结果第一行第一列
        public static object GetScalar_Proc(string procName, SqlParameter[] parameters)
        {
            using (SqlConnection conn = new SqlConnection(StrConn))
            {
                object oj = new object();
                try
                {
                    if (conn.State == ConnectionState.Closed)
                        conn.Open();
                    SqlCommand cmd = new SqlCommand(procName, conn);
                    cmd.CommandType = CommandType.StoredProcedure;
                    foreach (SqlParameter parameter in parameters)
                    {
                        cmd.Parameters.Add(parameter);
                    }
                    oj = cmd.ExecuteScalar();
                }
                catch (System.Data.SqlClient.SqlException ex)
                {
                    throw new Exception(ex.Message);
                }
                finally
                {
                    conn.Close();
                }
                return oj;
            }
        }
        #endregion


        #region 执行SQL查询
        #region 执行查询，返回一个 DataReader 对象 public SqlDataReader GetReader(string sql)
        /// <summary>
        /// 执行查询，返回一个 DataReader 对象
        /// </summary>
        public static SqlDataReader GetReader(string sqlstr)
        {

            // using (SqlConnection conn = new SqlConnection(StrConn))
            //  {
            SqlConnection conn = new SqlConnection(StrConn);
            if (conn.State == ConnectionState.Closed)
                conn.Open();
            SqlCommand cmd = new SqlCommand(sqlstr, conn);
            return cmd.ExecuteReader(CommandBehavior.CloseConnection);

            //  }




        }


        #endregion
        #region 执行SQL返回DataSet
        /// <summary>
        /// 执行sql返回DataSet
        /// </summary>
        /// <param name="ConnectionString"></param>
        /// <returns></returns>
        public static DataSet GetDataSet(string sql)
        {
            using (SqlConnection conn = new SqlConnection(StrConn))
            {
                DataSet ds = new DataSet();
                try
                {
                    if (conn.State == ConnectionState.Closed)
                        conn.Open();
                    SqlDataAdapter dap = new SqlDataAdapter(sql, conn);
                    //DA.SelectCommand.CommandTimeOut = 300;//
                    dap.SelectCommand.CommandTimeout = 300;
                    dap.Fill(ds, "ds");

                }
                catch (System.Data.SqlClient.SqlException ex)
                {
                    throw new Exception(ex.Message);
                }
                finally
                {
                    conn.Close();
                }
                return ds;

            }
        }
        #endregion
        #region 执行查询，返回结果第一行第一列 public object GetScalar_Proc(string sql)
        /// <summary>
        /// 执行查询，返回实体值
        /// </summary>
        public static object GetScalar(string sql)
        {
            using (SqlConnection conn = new SqlConnection(StrConn))
            {
                object oj = new object();
                try
                {
                    if (conn.State == ConnectionState.Closed)
                        conn.Open();
                    SqlCommand cmd = new SqlCommand(sql, conn);
                    oj = cmd.ExecuteScalar();
                }
                catch (System.Data.SqlClient.SqlException ex)
                {
                    throw new Exception(ex.Message);
                }
                finally
                {
                    conn.Close();
                }
                return oj;
            }
        }
        #endregion

        #endregion

        #region 执行参数化SQL查询
        /// <summary>   
        /// 执行参数化查询，返回SqlDataReader   
        /// </summary>   
        /// <param name="strSQL">查询语句</param>   
        /// <returns>SqlDataReader</returns>   
        public static SqlDataReader GetDataReader_Sp(string SQLString, params SqlParameter[] cmdParms)
        {
            SqlConnection connection = new SqlConnection(StrConn);
            SqlCommand cmd = new SqlCommand();
            try
            {
                PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                cmd.Parameters.Clear();
                return myReader;
            }
            catch (System.Data.SqlClient.SqlException e)
            {
                throw new Exception(e.Message);
            }

        }


        /// <summary>   
        /// 执行参数化查询语句，返回DataSet   
        /// </summary>   
        /// <param name="SQLString">查询语句</param>   
        /// <returns>DataSet</returns>   
        public static DataSet GetDataSet_Sp(string SQLString, params SqlParameter[] cmdParms)
        {
            using (SqlConnection connection = new SqlConnection(StrConn))
            {
                SqlCommand cmd = new SqlCommand();
                PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                {
                    DataSet ds = new DataSet();
                    try
                    {
                        da.Fill(ds, "ds");
                        cmd.Parameters.Clear();
                    }
                    catch (System.Data.SqlClient.SqlException ex)
                    {
                        throw new Exception(ex.Message);
                    }
                    return ds;
                }
            }
        }

        /// <summary>
        /// 执行参数化查询语句,返回结果第一行第一列  
        /// </summary>
        /// <param name="SQLString">查询语句</param>
        /// <param name="cmdParms">Parms</param>
        /// <returns>object</returns>
        public static object GetScalar_Sp(string SQLString, params SqlParameter[] cmdParms)
        {
            using (SqlConnection connection = new SqlConnection(StrConn))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    try
                    {
                        PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                        object obj = cmd.ExecuteScalar();
                        cmd.Parameters.Clear();
                        if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                        {
                            return null;
                        }
                        else
                        {
                            return obj;
                        }
                    }
                    catch (System.Data.SqlClient.SqlException e)
                    {
                        throw new Exception(e.Message);
                    }
                }
            }
        }
        private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, string cmdText, SqlParameter[] cmdParms)
        {
            if (conn.State == ConnectionState.Closed)
                conn.Open();
            cmd.Connection = conn;
            cmd.CommandText = cmdText;
            if (trans != null)
                cmd.Transaction = trans;
            cmd.CommandType = CommandType.Text;//cmdType;   
            if (cmdParms != null)
            {
                foreach (SqlParameter parm in cmdParms)
                    cmd.Parameters.Add(parm);
            }
        }
        #endregion
    }


}
